﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Configuration;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Text;
using System.Collections;

namespace TireService.Website
{
    public partial class Betal : System.Web.UI.Page
    {

        protected void Page_Init(object sender, EventArgs e)
        {
            // Register export button as full postback - otherwise it wount work because it is inside a update panel
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(this.btnPaypalPayment.FindControl("btnPaypalPayment"));
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Request.QueryString["Id"] != null)
            //{
            //    // Id exists
            //    try
            //    {
            //        Guid invoiceguidid = new Guid(Request.QueryString["Id"].ToString());

            //        // Instantiate database connection
            //        TireServiceDB db = new TireServiceDB();

            //        // Fetch invoice
            //        Invoice invoice = db.GetInvoice(invoiceguidid);
                    
            //        if (invoice != null)
            //        {
            //            // Payment is done through paypal
            //            if (Request.QueryString["Paypal"] != null)
            //            {
            //                if (Request.QueryString["Paypal"] == "Success")
            //                {
            //                    // Payment has been done
                                
            //                    // Update database
            //                    // Update invoice
            //                    //invoice.InvoiceStatusId = (int)Shared.InvoiceStatus.Paid;

            //                    // Get all invoicedetails
            //                    List<InvoiceDetail> details = invoice.InvoiceDetails.Where(p => p.CustomerSubscriptionId != null).ToList();

            //                    // Declare system userid
            //                    Guid userid = new Guid(ConfigurationManager.AppSettings["SystemUserId"].ToString());

            //                    int subscriptionid = 0;
            //                    int customersubscriptionid = 0;

            //                    // Fetch customer
            //                    Customer customer = db.GetCustomer(invoice.CustomerId);

            //                    // Update each customer subscription as paid
            //                    foreach (InvoiceDetail detail in details)
            //                    {
            //                        if (detail.CustomerSubscriptionId != null)
            //                        {
            //                            // Update subscription as paid
            //                            CustomerSubscription subscription = db.GetCustomerSubscription(Convert.ToInt32(detail.CustomerSubscriptionId));
            //                            subscription.Paid = true;

            //                            subscriptionid = subscription.SubscriptionId;
            //                            customersubscriptionid = subscription.CustomerSubscriptionId;

            //                            // TODO: Find car and change status
            //                            //Car car = db.GetCars()

            //                            // Create log on payment
            //                            CustomerSubscriptionLogBLL subscriptionBLL = new CustomerSubscriptionLogBLL();
            //                            subscriptionBLL.CreateCustomerSubscriptionLog(db, subscription, (int)Shared.SubscriptionLogAction.Paid, userid, "Online betaling");

            //                            // Send mail with confirmation on paid subscription
            //                            SendEmailSubscriptionPaid(customer.Email, customer.Name, customer.CustomerId.ToString(), subscriptionid.ToString(), customersubscriptionid.ToString());
            //                        }
            //                    }

            //                    // Commit changes to database
            //                    db.SubmitChanges();

            //                    // Send overall confirmation on paid invoice
            //                    SendEmail(customer.Email, customer.Name, invoice.InvoiceGuid.ToString(), invoice.InvoiceId);

            //                    // Show message
            //                    pPaymentCompleted.Visible = true;

            //                    pOnlinePayment.Visible = false;
            //                    pPaymentCancel.Visible = false;
            //                    pPaymentFailed.Visible = false;
            //                    pPaypalPayment.Visible = false;
            //                    pMessage.Visible = false;

            //                    lnkInvoice.HRef = "~/Reports/View/Faktura.aspx?InvoiceGuid=" + invoiceguidid.ToString();
            //                }
            //                else if (Request.QueryString["Paypal"] == "Cancel")
            //                {
            //                    // Customer cancelled payment
            //                    pPaymentCancel.Visible = true;
                                
            //                    pOnlinePayment.Visible = false;
            //                    pPaymentCompleted.Visible = false;
            //                    pPaymentFailed.Visible = false;
            //                    pPaypalPayment.Visible = false;
            //                }else
            //                {
            //                    // Error occured during payment
            //                    pPaymentFailed.Visible = true;

            //                    pOnlinePayment.Visible = false;
            //                    pPaymentCancel.Visible = false;
            //                    pPaymentCompleted.Visible = false;
            //                    pPaypalPayment.Visible = false;
            //                }
            //            }
            //            else
            //            {
            //                // Payment is done through PBS
            //                if (Request.QueryString["Action"] == "1")
            //                {
            //                    // Invoice has been paid - update invoice record

            //                    // Hide payment panel
            //                    pOnlinePayment.Visible = false;

            //                    // Update invoiceguidid
            //                    //invoice.InvoiceStatusId = (int)Shared.InvoiceStatus.Paid;

            //                    // Get all invoicedetails
            //                    List<InvoiceDetail> details = invoice.InvoiceDetails.Where(p => p.CustomerSubscriptionId != null).ToList();

            //                    // Declare system userid
            //                    Guid userid = new Guid(ConfigurationManager.AppSettings["SystemUserId"].ToString());

            //                    int subscriptionid = 0;
            //                    int customersubscriptionid = 0;

            //                    // Fetch customer
            //                    Customer customer = db.GetCustomer(invoice.CustomerId);

            //                    // Update each customer subscription as paid
            //                    foreach (InvoiceDetail detail in details)
            //                    {
            //                        if (detail.CustomerSubscriptionId != null)
            //                        {
            //                            // Update subscription as paid
            //                            CustomerSubscription subscription = db.GetCustomerSubscription(Convert.ToInt32(detail.CustomerSubscriptionId));
            //                            subscription.Paid = true;

            //                            subscriptionid = subscription.SubscriptionId;
            //                            customersubscriptionid = subscription.CustomerSubscriptionId;

            //                            // Create log on payment
            //                            CustomerSubscriptionLogBLL subscriptionBLL = new CustomerSubscriptionLogBLL();
            //                            subscriptionBLL.CreateCustomerSubscriptionLog(db, subscription, (int)Shared.SubscriptionLogAction.Paid, userid, "Online betaling");

            //                            // Send mail with confirmation on paid subscription
            //                            SendEmailSubscriptionPaid(customer.Email, customer.Name, customer.CustomerId.ToString(), subscriptionid.ToString(), customersubscriptionid.ToString());
            //                        }
            //                    }

            //                    // Commit changes to database
            //                    db.SubmitChanges();

            //                    // Send overall confirmation on paid invoice
            //                    SendEmail(customer.Email, customer.Name, invoice.InvoiceGuid.ToString(), invoice.InvoiceId);

            //                    // Show message
            //                    pPaymentCompleted.Visible = true;

            //                    pOnlinePayment.Visible = false;
            //                    pPaymentCancel.Visible = false;
            //                    pPaymentFailed.Visible = false;
            //                    pPaypalPayment.Visible = false;
            //                    pMessage.Visible = false;

            //                    lnkInvoice.HRef = "~/Reports/View/Faktura.aspx?InvoiceGuid=" + invoiceguidid.ToString();
            //                }
            //                else
            //                {
            //                    //// Check if invoice is already paid
            //                    //if (invoice.InvoiceStatusId == (int)Shared.InvoiceStatus.Paid)
            //                    //{
            //                    //    // Invoice was not found - show message
            //                    //    pMessage.Visible = true;
            //                    //    pOnlinePayment.Visible = false;
            //                    //    pPaymentCompleted.Visible = false;
            //                    //    pPaymentCancel.Visible = false;
            //                    //    pPaymentFailed.Visible = false;
            //                    //    pPaypalPayment.Visible = false;
            //                    //    lMessage.Text = "Denne faktura er allerede blevet betalt.<br><br><a href='http://www.mobilhjulskift.dk/Reports/View/Faktura.aspx?InvoiceGuid=" + invoiceguidid.ToString() + "' id='Link' target='_blank' runat='server'>Klik her for faktura</a>";
            //                    //}
            //                    //else
            //                    //{
            //                    //    // Invoice has NOT been paid, but customer is about to
                                    
            //                    //    // Add javascript that disables payment button when user clicks
            //                    //    btnPaypalPayment.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnPaypalPayment).ToString());

            //                    //    // Show payment panel
            //                    //    pPaypalPayment.Visible = true; // Only paypal possible right now
            //                    //    pMessage.Visible = false;
            //                    //    pOnlinePayment.Visible = false;
            //                    //    pPaymentCompleted.Visible = false;
            //                    //    pPaymentCancel.Visible = false;
            //                    //    pPaymentFailed.Visible = false;

            //                    //    // Set parameters for payment
            //                    //    hfCustomerId.Value = invoice.CustomerId.ToString();
            //                    //    hfEmail.Value = db.GetCustomerEmail(invoice.CustomerId);
            //                    //    hfAmount.Value = invoice.InvoiceDetails.Sum(p => p.Price).ToString();
            //                    //    hfInvoiceId.Value = invoice.InvoiceId.ToString();
            //                    //    hfInvoiceGuid.Value = invoice.InvoiceGuid.ToString();

            //                    //    // Show info to customer
            //                    //    hlInvoice.NavigateUrl = "~/Reports/View/Faktura.aspx?InvoiceGuid=" + invoice.InvoiceGuid.ToString();
            //                    //    lblAmount.Text = "Beløb: " + hfAmount.Value.ToString() + " kr";
            //                    //}
            //                }
            //            }
            //        }
            //        else
            //        {
            //            // Invoice was not found - show message
            //            pMessage.Visible = true;
            //            pPaypalPayment.Visible = false;
            //            pOnlinePayment.Visible = false;
            //            pPaymentCompleted.Visible = false;
            //            pPaymentCancel.Visible = false;
            //            pPaymentFailed.Visible = false;

            //            lMessage.Text = "Faktura blev ikke fundet";

            //            // TODO: Write more code
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        // Id not valid - redirect away from page
            //        Response.Redirect("~/Index.aspx");
            //    }
            //}
            //else
            //{
            //    // No Id exists - redirect away from page
            //    Response.Redirect("~/Index.aspx");
            //}
        }

        /// <summary>
        /// Function that sends email to customer confirmation on payment for specific customer subscription
        /// </summary>
        /// <param name="CustomerEmail">Customer email that this email will be send to</param>
        /// <param name="CustomerName">Name on customer</param>
        /// <param name="CustomerId">Id on customer</param>
        /// <param name="SubscriptionId">Id on subscription</param>
        /// <param name="CustomerSubscriptionId">Unik customer subscription id</param>
        private void SendEmailSubscriptionPaid(string CustomerEmail, string CustomerName, string CustomerId, string SubscriptionId, string CustomerSubscriptionId)
        {
            string Subject = "Abonnement: " + CustomerId + "-" + SubscriptionId + "-" + CustomerSubscriptionId + "betalt";
            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
            Shared email = new Shared();

            Hashtable templateVars = new Hashtable();

            // Send email to customer
            templateVars.Add("CustomerName", CustomerName);
            templateVars.Add("CustomerId", CustomerId);
            templateVars.Add("SubscriptionId", SubscriptionId);
            templateVars.Add("CustomerSubscriptionId", CustomerSubscriptionId);
            Shared.Parser parser = new Shared.Parser(Server.MapPath("~/HtmlTemplates/BetalingAbonnement.htm"), templateVars);

            // Send email to customer with us on bcc
            email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), parser.Parse(), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null);
        }

        /// <summary>
        /// Function that sends email to customer confirmation on paid invoice
        /// </summary>
        /// <param name="CustomerEmail">Customer email that this email will be send to</param>
        /// <param name="CustomerName">Name on customer</param>
        /// <param name="InvoiceGuid">Unik Guid number for invoice</param>
        /// <param name="InvoiceId">Id on Invoice</param>
        private void SendEmail(string CustomerEmail, string CustomerName, string InvoiceGuid, int InvoiceId)
        {
            string Subject = "Betaling gennemført - Faktura " + InvoiceId.ToString();
            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
            Shared email = new Shared();

            Hashtable templateVars = new Hashtable();

            // Send email to customer
            templateVars.Add("CustomerName", CustomerName);
            templateVars.Add("InvoiceGuid", InvoiceGuid);
            templateVars.Add("InvoiceId", InvoiceId);
            Shared.Parser parser = new Shared.Parser(Server.MapPath("~/HtmlTemplates/Betaling.htm"), templateVars);

            // Send email to customer with us on bcc
            email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), parser.Parse(), Subject, true, test, ConfigurationManager.AppSettings["EmailAddress"].ToString(), null, null);
        }

        /// <summary>
        /// Button function for handling online payment through PBS
        /// </summary>
        protected void btnPayment_Click(object sender, EventArgs e)
        {
            try
            {
                string amount = string.Format("{0:N}", hfAmount.Value).Replace(".", "").Replace(",", "");
                string invoiceguid = hfInvoiceGuid.Value.ToString();
                string invoiceid = hfInvoiceId.Value.ToString();
                string acceptURL = "www.mobilhjulskift.dk/Betal.aspx?Id=" + invoiceguid + "Action=1";
                string declineURL = "www.mobilhjulskift.dk/BetalFejl.aspx?Id=" + invoiceguid;

                NameValueCollection data = HelperFunctions.OnlinePayment(amount,
                                              invoiceid,
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopCurrency"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopMd5Key"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopId"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopOrderPrefix"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopPayType"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopCardType"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["ShopLanguage"]),
                                              acceptURL,
                                              declineURL
                                             );

                HttpHelper.RedirectAndPOST(this.Page, Convert.ToString(ConfigurationManager.AppSettings["ShopAuthURL"]), data);
            }
            catch (Exception ex)
            {
                // Error occured during payment
                pPaymentFailed.Visible = true;

                pOnlinePayment.Visible = false;
                pPaymentCancel.Visible = false;
                pPaymentCompleted.Visible = false;
                pPaypalPayment.Visible = false;

                // Send email to mobil hjulskift with error and contact information on customer
                string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                string message = String.Format("Systemet fejlede ved forsøg på at betale faktura<br><br>KundeId: {0}<br>Faktura: {1}<br>Systemfejl: {2}", hfCustomerId.Value.ToString(), hfInvoiceId.Value.ToString(), ex.Message);

                Shared email = new Shared();
                email.SendEmail(emailaddress, emailaddress, message, "Fejl ved betaling", true, test, null, null, null);
            }
        }

        /// <summary>
        /// Button function for handling online payment through PayPal
        /// </summary>
        protected void btnPaypalPayment_Click(object sender, EventArgs e)
        {
            try
            {
                // *** Set a flag so we know we redirected to minimize spoofing
                Session["PayPal_Redirected"] = "True";

                string customerid = hfCustomerId.Value.ToString();
                string amount = string.Format("{0:N}", hfAmount.Value.Replace(",", "."));
                string invoiceguid = hfInvoiceGuid.Value.ToString();
                string invoiceid = hfInvoiceId.Value.ToString();
                //string NotifyURL = Convert.ToString(ConfigurationManager.AppSettings["PayPalNotifyURL"]) + "?Id=" + invoiceguid + "Action=1";


                NameValueCollection data = HelperFunctions.PaypalOnlinePayment(customerid,
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalReturnURL"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalCancelURL"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalBusinessEmail"]),
                                              Convert.ToString(ConfigurationManager.AppSettings["LogoURL"]),
                                              hfEmail.Value.ToString(),
                                              Convert.ToString(ConfigurationManager.AppSettings["PayPalCurrencyCode"]),
                                              "Mobilhjulskift abonnement",
                                              amount,
                                              invoiceguid,
                                              invoiceid
                                             );

                HttpHelper.RedirectAndPOST(this.Page, Convert.ToString(ConfigurationManager.AppSettings["PayPalAuthURL"]), data, "_xclick");
            }
            catch (Exception ex)
            {
                // Error occured during payment
                pPaymentFailed.Visible = true;

                pOnlinePayment.Visible = false;
                pPaymentCancel.Visible = false;
                pPaymentCompleted.Visible = false;
                pPaypalPayment.Visible = false;

                // Send email to mobil hjulskift with error and contact information on customer
                string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                string message = String.Format("Systemet fejlede ved forsøg på at betale faktura<br><br>KundeId: {0}<br>Faktura: {1}<br>Systemfejl: {2}", hfCustomerId.Value.ToString(), hfInvoiceId.Value.ToString(), ex.Message);

                Shared email = new Shared();
                email.SendEmail(emailaddress, emailaddress, message, "Fejl ved betaling", true, test, null, null, null);
            }
        }
    }
}